<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name" :rules="[{ required: true, message: '单据名称为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="单据名称" tooltip="单据的名称" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_CodeType_FormItem"
								prop="Entity.CodeType"
								:rules="[{ required: true, message: '单据类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="单据类型" tooltip="业务单据类型（使用模型名称）" />
								</template>
								<el-cascader
									:options="stateData.allBillList"
									:props="{ checkStrictly: false, emitPath: false, label: 'Text', value: 'Id', children: 'Children' }"
									clearable
									filterable
									class="w100"
									v-model="stateData.vmModel.Entity.CodeType"
									@change="onCodeTypeChange"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_PcRoute_FormItem" prop="Entity.PcRoute">
								<template #label>
									<WtmLabelTooltip label="PC路由地址" tooltip="单据的PC访问路由地址" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.PcRoute" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_MobileRoute_FormItem" prop="Entity.MobileRoute">
								<template #label>
									<WtmLabelTooltip label="移动端路由地址" tooltip="单据的移动端访问路由地址" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.MobileRoute" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysBillRouteApi as api } from '/@/views/_admin/sysbillroute/api';
import other from '/@/utils/other';
import { ISysBillRouteVm } from '/@/views/_admin/sysbillroute/api/interface';
import { IViewModel } from '/@/types/common';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const stateData = reactive<IViewModel<ISysBillRouteVm>>({
	vmModel: {
		Entity: {
			ID: null,
			Name: null,
			CodeType: null,
			PcRoute: null,
			MobileRoute: null,
		},

		ActionName: null,
		IsMyApprove: null,
	},
	allBillList: [],
});

const handleApiResponse = (response: any, isSubmit = false) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};
// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response, isSubmit))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {},
		false
	);
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysCodeRule/GetBillList', [], false).then((x) => {
			stateData.allBillList = x;
		}),
		api()
			.get(stateData.vmModel.Entity.ID ?? '')
			.then((x) => other.setValue(stateData.vmModel, x)),
	]);
};
// 编码类型改变时的处理
const onCodeTypeChange = (value: string) => {
	if (value) {
		// 在所有选项中查找选中的项
		const findItemByValue = (items: any[], targetValue: string): any => {
			for (const item of items) {
				if (item.Id === targetValue) {
					return item;
				}
				if (item.Children && item.Children.length > 0) {
					const found = findItemByValue(item.Children, targetValue);
					if (found) return found;
				}
			}
			return null;
		};

		const selectedItem = findItemByValue(stateData.allBillList, value);
		if (selectedItem && selectedItem.Tag) {
			stateData.vmModel.Entity.Name = selectedItem.Tag;
		}
	}
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
